package com.itheima.controller.store.question;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Catalog;
import com.itheima.domain.Company;
import com.itheima.domain.Question;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {


    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String page = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");

        List<Question> questionList=questionService.findAll(page,pageSize);
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);

        req.setAttribute("page",pageInfo);

        req.getRequestDispatcher("/pages/store/question/list.jsp").forward(req,resp);


    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        List<Company> companyList =questionService.findAll1();
        List<Catalog> catalogList=questionService.findAll2();

        req.setAttribute("companyList",companyList);
        req.setAttribute("catalogList",catalogList);

        req.getRequestDispatcher("/pages/store/question/add.jsp").forward(req,resp);
    }
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }


            // --处理form表单提交过来的普通数据
            //将数据获取到，封装成一个对象
            Question question = BeanUtil.fillBean(fileItems,Question.class);
            //调用业务层接口save
         String id  = questionService.save(question,flag);

            // --处理form表单提交过来的文件数据
            for(FileItem item : fileItems){
                //5.当前表单是否是文件表单
                if(!item.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    item.write(new File(this.getServletContext().getRealPath("upload"),id));
                }
            }
        }


        findAll(req,resp);
    }
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("id");
        Question question=questionService.findById(id);

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(question);
        req.setAttribute("question",question);

        List<Company> companyList =questionService.findAll1();
        List<Catalog> catalogList=questionService.findAll2();

        req.setAttribute("companyList",companyList);
        req.setAttribute("catalogList",catalogList);

        req.getRequestDispatcher("/pages/store/question/update.jsp").forward(req,resp);
    }
    protected void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            // --处理form表单提交过来的普通数据
            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }



            //将数据获取到，封装成一个对象
            Question question = BeanUtil.fillBean(fileItems,Question.class);
            //调用业务层接口save
            questionService.edit(question,flag);

            // --处理form表单提交过来的文件数据
            for(FileItem item : fileItems){
                //5.当前表单是否是文件表单
                if(!item.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    item.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                }
            }
        }

        findAll(req,resp);
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String ids = req.getParameter("id");
        questionService.delete(ids);


        findAll(req,resp);
    }
}
